package com.cg.offer;

import com.cg.leetcode.ListNode;
import org.junit.Test;

import java.util.Arrays;
import java.util.Stack;

/**
 * 剑指Offer 06.从尾到头打印链表
 *
 * @program: LeetCode->Offer_06
 * @description: 剑指Offer 06.从尾到头打印链表
 * @author: cg
 * @create: 2022-03-10 14:52
 **/
public class Offer_06 {
    @Test
    public void test06() {
        ListNode head = new ListNode(1);
        head.next = new ListNode(3);
        head.next.next = new ListNode(2);
        System.out.println(Arrays.toString(reversePrint(head)));
    }

    /**
     * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
     * <p>
     * 示例 1：
     * 输入：head = [1,3,2]
     * 输出：[2,3,1]
     * <p>
     * 限制：
     * 0 <= 链表长度 <= 10000
     *
     * @param head
     * @return
     */
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        while (head != null) {
            stack.push(head.val);
            head = head.next;
        }
        int[] arr = new int[stack.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = stack.pop();
        }
        return arr;
    }
}
